<template>
	<view class="page">
		<view class="page-banner">
			<swiper :autoplay="true" :interval="2000" :duration="1000" indicator-dots circular
				indicator-color="rgba(0, 0, 0, .3)" indicator-active-color="#fff" class="swiper-item_box">
				<!-- 	<swiper-item class="banner_image" @click="goSecretary">
					<image src="https://mysmallapp.oss-cn-shanghai.aliyuncs.com/aixz/img/homeBanner1.png"
						mode="widthFix"></image>
				</swiper-item> -->
				<!-- <swiper-item class="banner_image" @click="goAiWriting">
					<image src="https://iflytts.oss-cn-qingdao.aliyuncs.com/images/invite/banner.png" style="width: 100%;"
						mode="widthFix"></image>
				</swiper-item> -->
				<swiper-item class="banner_image">
					<image src="https://iflytts.oss-cn-qingdao.aliyuncs.com/images/aixz/a.jpg" style="width: 100%;"
						mode="widthFix"></image>
				</swiper-item>
				<swiper-item class="banner_image">
					<image src="https://iflytts.oss-cn-qingdao.aliyuncs.com/images/aixz/b.jpg" style="width: 100%;"
						mode="widthFix"></image>
				</swiper-item>
			</swiper>
			<!-- <image mode="scaleToFill" style="width: 100%;height: 100%" src="https://iflytts.oss-cn-qingdao.aliyuncs.com/images/invite/banner.png"></image> -->
		</view>
		<view class="pagePositioning"></view>
		<view class="task">
			<view class="task-content">
				<view class="day">
					每日任务
					<text class="free">免费获得次数</text>
				</view>
				<view v-for="(item,index) in tasklist" :key="index">
					<view class="tasklist" @click="invitation(index)">
						<view class="tasklist-left">
							<image class="tasklist-img" :src="item.img" mode=""></image>
							<view class="tasklist-item">
								{{ item.title }}
								<view class="tasklist-item-reward">
									{{ item.desc }}
								</view>
								<view v-if="index == 4" class="tasklist-item-schedule">
									进度{{adNum}}/5
								</view>
								<view v-else class="tasklist-item-schedule">
									{{ item.schedule }}
								</view>
							</view>
						</view>
						<view class="tasklist-right">
							{{ item.gotext }}
						</view>
					</view>
					<view class="line" v-if="index != 4"></view>
				</view>
			</view>
		</view>

		<view class="getvip" @click="govip">
			<view class="btn">
				<image src="../../static/markMoney/member.png" mode=""></image>
				开通会员
			</view>
		</view>

		<view class="dialog-shadow" v-if="shareShow" @click="closeInvitation">
			<view class="dialog-shadow-bottom">
				<button plain="true" open-type="share" style="border:none" class="dialog-shadow-bottom-item">
					<view class="dialog-shadow-bottom-item-img">
						<image mode="scaleToFill" style="width: 100%;height: 100%" src="../../static/markMoney/wx.png">
						</image>
					</view>
					<view class="dialog-shadow-bottom-item-text">微信好友/群</view>
				</button>
				<view class="dialog-shadow-bottom-item" @click="posters" v-if="authorizationBtn">
					<view class="dialog-shadow-bottom-item-img">
						<image mode="scaleToFill" style="width: 100%;height: 100%" src="../../static/markMoney/tp.png">
						</image>
					</view>
					<view class="dialog-shadow-bottom-item-text">分享海报</view>
				</view>
				<button class="dialog-shadow-bottom-item" style="border:none" :plain="true" open-type="openSetting"
					@opensetting="opensetting" v-else>
					<view class="dialog-shadow-bottom-item-img">
						<image mode="scaleToFill" style="width: 100%;height: 100%" src="../../static/markMoney/tp.png">
						</image>
					</view>
					<view class="dialog-shadow-bottom-item-text">分享海报</view>
				</button>
				<view class="dialog-shadow-bottom-item" @click="shareLinks">
					<view class="dialog-shadow-bottom-item-img">
						<image mode="scaleToFill" style="width: 100%;height: 100%" src="../../static/markMoney/lj.png">
						</image>
					</view>
					<view class="dialog-shadow-bottom-item-text">分享链接</view>
				</view>
			</view>
		</view>
		
		<view v-if="showCanvas" class="canvasView" :style="{'z-index':showCanvas?'300':'0'}">
			<canvas :style="{'width':canvasWidth+'px', 'height':canvasHeight+'px'}" canvas-id="myCanvas" />
		</view>
	</view>
</template>
<script>
	import {
		myShowLoading,
		myHideLoading,
	} from "../../utils/showToast.js";
	import {
		apiMixUrlKeyApi,
		apiMixUrlApi
	} from "../../api/assemb";
	import store from '../../store/idnex.js'

	export default {
		data() {
			return {
				tasklist: [{
					img: '../../static/markMoney/invite.png',
					title: '邀请新用户',
					desc: '邀请1人奖1条,仅限一级用户',
					schedule: '不限制邀请上限',
					gotext: '去邀请'
				}, {
					img: '../../static/markMoney/media.png',
					title: '新媒体赚会员',
					desc: '发布视频即可兑换三天以上会员',
					schedule: '审核通过后奖励',
					gotext: '去推广'
				}, {
					img: '../../static/markMoney/money.png',
					title: '推广赚钱',
					desc: '邀请新用户充值获得50%的提成',
					schedule: '不限制邀请上限',
					gotext: '去推广'
				}, {
					img: '../../static/markMoney/follow.png',
					title: '关注公众号',
					desc: '防止丢失，关注不迷路',
					schedule: '',
					gotext: '去关注'
				}, {
					img: '../../static/markMoney/watchad.png',
					title: '看广告得次数',
					desc: '观看广告奖1条，每日限5次',
					schedule: '',
					gotext: '去完成'
				}],
				userid: '',
				show: false,
				shareShow: false,
				showCanvas: false,
				canvasHeight: 500,
				canvasWidth: 300,
				authorizationBtn: true,
				rewardedVideoAd: '',
				adNum:0
			}
		},
		onShareAppMessage(res) {
			const that = this
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target, 'res.target')
			}
			return {
				title: 'AI写作神器，一键改写变原创。',
				path: "pages/home/home?userid=" + that.userid,
				imageUrl: "https://iflytts.oss-cn-qingdao.aliyuncs.com/wxapp/xze/6.png",
				success: function(res) {
					console.log(
						"--------------转发成功--------------------",
						res,
						that.userid
					);
				}
			}
		},
		onLoad() {

		},
		onShow() {
			var time = new Date();
			let baseinfo = uni.getStorageSync('baseinfo');
			console.log('baseinfo', baseinfo);
			this.userid = baseinfo.userid;

			this.rewardedVideoAd = uni.createRewardedVideoAd({
				adUnitId: 'adunit-dffb0edd8111d6df',
			})

			this.rewardedVideoAd.onError((err) => {
				uni.showToast({
					title: '出错了，请刷新重试！',
					icon: 'fail',
					duration: 2000
				})
			})
			
			// 控制广告次数
			if(uni.getStorageSync('watchad')){
				this.adNum = uni.getStorageSync('watchad');
			} else {
				this.adNum = 0;
			}
			// 更新剩余次数
			this.getFrequency()
		}, 
		methods: {
			govip() {
				if (uni.getStorageSync('OS') != 'ios') {
					uni.navigateTo({
						url: '/pages/paymentCenter/paymentCenter'
					});
				} else {
					if (getApp().globalData.iosPay == 0) {
						uni.showModal({
							title: '提示',
							content: '由于相关规范，IOS功能暂不可用',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					} else if (getApp().globalData.iosPay == 1) {
						// uni.navigateTo({
						// 	url: '/pages/goods/goods'
						// });
						uni.navigateTo({
							url:'/pages/webview/view'
						});
					}
				}
			},
			// 获取次数
			getFrequency() {
				apiMixUrlApi({}, 1042, 'GetPaymentInfo').then(data => {
					if (data.descinfo == "success") {
						uni.setStorageSync('frequency', data.coins)
					}
				});
			},
			// 观看广告
			watchAd() {
				var that = this;
				//看激励视频广告
				this.rewardedVideoAd.show()
					.catch(() => {
						this.rewardedVideoAd.load()
							.then(() => this.rewardedVideoAd.show())
							.catch(err => {
								uni.showToast({
									icon: 'none',
									position: 'bottom',
									title: '视频拉取失败，请稍后再试！'
								});
								return
							})
					})
				this.rewardedVideoAd.onLoad(() => {
					console.log('onLoad event')
					// 当激励视频被关闭时，默认预载下一条数据，加载完成时仍然触发 `onLoad` 事件
				})
				this.rewardedVideoAd.onError((err) => {
					uni.showToast({
						title: '出错了，请刷新重试！',
						icon: 'fail',
						duration: 2000
					})
				})
				try {
					if (this.rewardedVideoAd.closeHandler) {
						this.rewardedVideoAd.offClose(this.rewardedVideoAd.closeHandler);
						console.log("rewardedVideoAd.offClose卸载成功");
					}
				} catch (e) {
					console.log("rewardedVideoAd.offClose 卸载失败");
					console.error(e);
				}
				this.rewardedVideoAd.closeHandler = function(res) {
					// 用户点击了【关闭广告】按钮
					if (res && res.isEnded || res === undefined) {
						// 正常播放结束，可以下发游戏奖励
						console.log("播放完毕");
						if(uni.getStorageSync('watchad') > 0){
							that.adNum += 1;
							let num = uni.getStorageSync('watchad');
							uni.setStorageSync('watchad',num+1);
						} else {
							that.adNum += 1;
							uni.setStorageSync('watchad', 1);
						}
						
						let prams = {
							coins: 1,
							descinfo:'观看广告'
						}
						apiMixUrlKeyApi(prams, '1031', 'EarnCoins').then(res => {
							console.log('res===>', res)
							if(Number(uni.getStorageSync('frequency')) > 0){
								let a = Number(uni.getStorageSync('frequency')) + 1
								uni.setStorageSync('frequency', a)
							} else {
								uni.setStorageSync('frequency', res.data.coins)
							}
						})
					}
				};
				this.rewardedVideoAd.onClose(this.rewardedVideoAd.closeHandler);
			},
			invitation(index) {
				if (index == 0) {
					this.shareShow = true
				} else if (index == 1) {
					uni.navigateTo({
						url: "/pages/newmedia/newmedia"
					})
				} else if (index == 2) {
					uni.navigateTo({
						url: "./markMoneys"
					})
				} else if (index == 3) {
					uni.navigateTo({
						url: "/pages/webview/view"
					})
				} else {
					if(this.adNum == 5){
						wx.showModal({
							title: "提示",
							content: "今日广告次数已用完",
							showCancel: false,
							success(ser) {
							},
						});
					} else {
						this.watchAd()
					}
				}
			},
			closeInvitation() {
				this.shareShow = false
			},
			opensetting(e) {
				console.log('opensettinge', e)
				if (!e.detail.authSetting["scope.writePhotosAlbum"]) {
					uni.showModal({
						title: '提示',
						content: '你必须授权《添加到相册》权限才能使用',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else {
					this.posters()
				}
			},
			gofriend() {
				uni.navigateTo({
					url: '/pages_markMoney/promotion4/promotion4'
				});
			
			},
			gobill() {
				uni.navigateTo({
					url: '/pages_markMoney/promotion3/promotion3'
				});
			
			},
			goearnings() {
				let that = this
				console.log('this.cash', this.cash)
				uni.navigateTo({
					url: '/pages_markMoney/promotion2/promotion2' +
						`?cash=${that.cash}&totalCash=${that.totalCash}&alreadyCash=${that.alreadyCash}&inviteNum=${that.inviteNum}`
				});
			},
			async posters() {
				var that = this;
				myShowLoading("正在生成海报");
				let c1 = new wx.cloud.Cloud({
					// 资源方 AppID
					resourceAppid: getApp().globalData.resourceAppid,
					// 资源方环境 ID
					resourceEnv: getApp().globalData.resourceEnv,
				});
				await c1.init();
				c1.callFunction({
					name: "getUnlimited",
					data: {
						idForPosters: this.userid,
					},
				}).then((res) => {
					const fs = wx.getFileSystemManager();
					const filePath = wx.env.USER_DATA_PATH + "/myercode.png";
					console.log('filePath==>', filePath)
					fs.writeFile({
						// 写文件
						filePath: filePath,
						data: res.result.buffer,
						encoding: "binary", //二进制流文件必须是 binary
						success(res) {
							that.drawImage(filePath);
						},
					});
				});
			},
			shareLinks() {
				var that = this;
				let userid = that.userid
				wx.showModal({
					title: "温馨提示",
					content: "成功获取您的专属推广链接，复制链接分享好友",
					showCancel: false,
					confirmText: "复制",
					success(ser) {
						wx.setClipboardData({
							data: "一键AI文案改写，百万大V们都在用，点击免费体验伪原创生成器: https://mp3.peiyintek.cn/wxlink3.html?userid=" +
								userid + "&type=" + store.state.appid,
							success() {
								wx.showToast({
									title: "复制成功",
									icon: "success",
									duration: 1200,
								});
							},
						});
					},
				});
			},
			drawImage(filePath) {
				var that = this;
				const ctx = wx.createCanvasContext("myCanvas", that);
				// 获取图片信息，要按照原图来绘制，否则图片会变形
				wx.getImageInfo({
					src: "https://iflytts.oss-cn-qingdao.aliyuncs.com/qrCode/wx_2022_5_25_fxt1683612581221.jpg",
					success: function(res) {
						// 根据 图片的大小 绘制底图 的大小
						console.log(" 绘制底图 的图片信息》》》", res);
						let imgW = res.width / 4.5;
						let imgH = res.height / 4.5;
						let imgPath = res.path;
						that.showCanvas = true
						that.canvasHeight = imgH
						that.canvasWidth = imgW
						// 绘制底图 用原图的宽高比绘制
						ctx.drawImage(imgPath, 0, 0, imgW, imgH);
						wx.getImageInfo({
							src: filePath, // 二维码图片的路径
							success: function(res) {
								console.log(" 绘制二维码》》》", res);
								// 绘制二维码
								ctx.drawImage(res.path, (imgW / 2 - 115), (imgH - 135), 100, 100);
								ctx.draw();
								setTimeout(() => {
									wx.canvasToTempFilePath({
											canvasId: "myCanvas",
											success: function(res) {
												console.log(
													"合成的带有小程序码的图片success》》》",
													res);
												let tempFilePath = res
													.tempFilePath;
												//保存到相册
												wx.saveImageToPhotosAlbum({
													filePath: tempFilePath,
													success(res) {
														myHideLoading();
														wx.showModal({
															title: "温馨提示",
															content: "海报保存成功，可在相册中查看并分享",
															showCancel: false,
															success(
																res
															) {
																that.showCanvas =
																	false
																wx
																	.clear;
															},
														});
													},
			
													fail(res) {
														myHideLoading();
														wx.showModal({
															title: "温馨提示",
															content: "图片保存失败，请重试，并授权添加到相册功能",
															showCancel: false,
														});
														that.showCanvas =
															false
														that.authorizationBtn =
															false
													},
												});
												console.log("合成的带有小程序码的图片的信息》》》",
													res);
											},
											fail: function(res) {
												console.log(
													"生成的图拍呢 失败 fail fail fail ",
													res);
												myHideLoading();
												wx.showModal({
													title: "温馨提示",
													content: "小程序码图片合成失败，请重试",
													showCancel: false,
												});
											},
										},
										that
									);
								}, 1500);
							},
						});
					},
					fail(res) {
						myHideLoading();
						wx.showModal({
							title: "温馨提示",
							content: "图片信息获取失败，请重试",
							showCancel: false,
						});
					},
				});
			},
			invite() {
				let content = "暂无佣金可提现，快去分享赚佣金吧";
				if (this.cash > 0 && this.cash < 200) {
					content = "满200才能提现，继续分享赚佣金吧";
				} else if (this.cash >= 200) {
					content = "可在“用户中心->联系客服”联系客服提现";
				}
				wx.showModal({
					content: content,
					showCancel: !1,
					confirmText: "明白",
					success: function(t) {},
				});
			}
		}
	}
</script>

<style>
	page {
		background-color: #F5F5F5;
	}
</style>

<style lang="scss" scoped>
	.page-banner {
		width: 100%;
		height: 272rpx;
	}

	.task {
		position: absolute;
		top: 215rpx;
		width: 100%;
		display: flex;
		justify-content: center;

		.task-content {
			width: 689rpx;
			padding-bottom: 50rpx;
			background: #FFFFFF;
			border-radius: 15rpx;

			.day {
				margin-top: 37rpx;
				margin-left: 35rpx;
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #333333;

				.free {
					font-size: 21rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #909090;
					margin-left: 10rpx;
				}
			}

			.tasklist {
				display: flex;
				justify-content: space-between;
				margin-left: 41rpx;
				margin-right: 35rpx;
				margin-top: 38rpx;

				.tasklist-left {
					display: flex;

					.tasklist-img {
						width: 85rpx;
						height: 85rpx;
					}

					.tasklist-item {
						font-size: 27rpx;
						font-family: PingFang SC;
						font-weight: bold;
						color: #333333;
						margin-left: 28rpx;
						margin-top: 8rpx;

						.tasklist-item-reward {
							font-size: 21rpx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #909090;
							margin-top: 14rpx;
							margin-bottom: 11rpx;
						}

						.tasklist-item-schedule {
							font-size: 21rpx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #00C56F;
						}
					}
				}

				.tasklist-right {
					width: 119rpx;
					height: 49rpx;
					background: #4E98FF;
					border-radius: 24rpx;
					font-size: 21rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #FFFFFF;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-top: 22rpx;
				}
			}

			.line {
				width: 614rpx;
				height: 1rpx;
				background: #f5f5f5;
				margin: 0 auto;
				margin-top: 33rpx;
			}
		}
	}

	.getvip {
		position: fixed;
		width: 100%;
		bottom: 30rpx;
		display: flex;
		justify-content: center;

		.btn {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 515rpx;
			height: 86rpx;
			background: #4E98FF;
			border-radius: 43rpx;
			color: #fff;

			image {
				width: 43rpx;
				height: 31rpx;
				margin-right: 11rpx;
			}
		}
	}

	.dialog-shadow {
		width: 100%;
		height: 100vh;
		background-color: rgba(0, 0, 0, .4);
		position: fixed;
		top: 0rpx;
		z-index: 20;

		.dialog-shadow-bottom {
			width: 100%;
			height: 200rpx;
			position: absolute;
			bottom: 0rpx;
			border-radius: 10rpx;
			background-color: #fff;
			display: flex;

			.dialog-shadow-bottom-item {
				width: 33%;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;

				.dialog-shadow-bottom-item-img {
					width: 80rpx;
					height: 80rpx;
				}

				.dialog-shadow-bottom-item-text {
					width: 100%;
					height: 50rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 24rpx;
					margin-top: 10rpx;
				}
			}
		}
	}
	
	.canvasView {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}
	
	.pagePositioning {
		height: 1200rpx;
	}
</style>
